//
//  ReadDetaliCommentViewController.m
//  Slice
//
//  Created by lanou on 16/6/21.
//  Copyright © 2016年 wangjinchao. All rights reserved.
//

#import "ReadDetaliCommentViewController.h"


@interface ReadDetaliCommentViewController ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation ReadDetaliCommentViewController

- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return  _dataArray;
}

- (void)creatTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 55) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

- (void)getData {
    [RequestTool requsetWithType:POST URLString:GETCOMMENT_url paremeter:@{@"contentid":self.contentId} callBack:^(NSData *data, NSError *error) {
        if (data == nil) {
            return ;
        }
        
        NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
        
        for (NSDictionary *dic in jsonData[@"data"][@"list"]) {
            [self.dataArray addObject:[CommentModel modelWithDiction:dic]];
        } 
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }];
}




- (void)viewDidLoad {
    [super viewDidLoad];
    [self getData];
    
    [self creatTableView];
    
    self.keyBoardView = [[[NSBundle mainBundle] loadNibNamed:@"ReadCommentKeyboardView" owner:self options:nil] lastObject];
    [self.view addSubview:self.keyBoardView];

    [self.tableView registerNib:[UINib nibWithNibName:@"ReadCommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"123"];
    
    [self.keyBoardView.sendBtn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDisappear:) name:UIKeyboardWillHideNotification object:nil];

}

//发送信息
- (void)sendMessage {
    [self.view endEditing:YES];
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"user"];
    
    NSString *auth = dic[@"auth"];
    if (self.keyBoardView.messageTF.text == nil) {
        return;
    } else {
        NSDictionary *DIC = @{@"contentid":self.contentId,@"content":self.keyBoardView.messageTF.text,@"auth":auth};
        
        [RequestTool requsetWithType:POST URLString:ADDCOMMENT_url paremeter:DIC
                            callBack:^(NSData *data, NSError *error) {
            if (data == nil) {
                return ;
            }

            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            NSNumber *result = jsonDic[@"result"];
            if (result.intValue == 1) {
                [self.dataArray removeAllObjects];
                [self getData];
            } else {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:jsonDic[@"data"][@"msg"] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil];
                [alert addAction:action];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
         self.keyBoardView.messageTF.text = nil;
    }
}

#pragma mark -代理方法-
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentModel *model =  self.dataArray[indexPath.row];
    
   CGFloat kh = [GetHeight getHeighWithstring:model.content width:kWidth - 40];
    return 100 + kh;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ReadCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"123" forIndexPath:indexPath];
    
    [cell getDataWith:self.dataArray[indexPath.row]];

    return cell;
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView beginUpdates];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        CommentModel *model = self.dataArray[indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [self.dataArray removeObjectAtIndex:indexPath.row];
        
       NSString *str = model.userinfo[@"uname"];
       NSString *str1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"user"][@"uname"];
        
        if ([str isEqualToString:str1]) {
            [RequestTool requsetWithType:POST URLString:DELCOMMENT_url paremeter:@{@"contentid":self.contentId,@"commentid":model.contentid, @"auth":[[NSUserDefaults standardUserDefaults] objectForKey:@"user"][@"auth"]} callBack:^(NSData *data, NSError *error) {
                if (data == nil) {
                    return ;
                }
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
                
                NSNumber *result = dic[@"result"];
                if (result.intValue == 0) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:dic[@"data"][@"msg"] preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil];
                    [alert addAction:action];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }];
        }
        
    }
    [tableView endUpdates];
}















//键盘的通知方法
- (void)keyboardWillAppear:(NSNotification*)notification11 {
    
    CGRect rect = [[notification11.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    
    CGFloat keyBoardHieght = rect.size.height;
    
    CGRect newRect = self.keyBoardView.frame;
    newRect.origin.y -= keyBoardHieght;
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    CGFloat cc = [[notification11.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    

        [UIView animateWithDuration:cc animations:^{
            self.keyBoardView.frame = newRect;
        }];
}





//输入框编辑完成以后，当键盘即将消失时，将视图恢复到原始状态

- (void)keyboardWillDisappear:(NSNotification *)info {
    
    CGFloat cc = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
   [UIView animateWithDuration:cc animations:^{
            self.keyBoardView.frame = CGRectMake(0 , kHeight - 55, kWidth, 55);
        }];
   
 
}





@end
